package thesis.filesharing.web.tags;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import thesis.filesharing.model.Student;
import thesis.filesharing.web.auth.AuthUtil;
import thesis.filesharing.web.auth.AuthenticationUserDetails;
import thesis.filesharing.web.viewmodel.GroupViewModel;

import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;

public class TagFunctions {
	
	public static AuthenticationUserDetails checkAuthentication() {
		Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if (obj instanceof String) {
			return null;
		} else {
			return (AuthenticationUserDetails) obj;
		}
	}
	
	public static Boolean isUserInRole(String roleName) {
		Object obj = checkAuthentication();
		if (obj == null) {
			return false;
		}
		AuthenticationUserDetails authUser = (AuthenticationUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		HashSet<GrantedAuthority> authorities = (HashSet<GrantedAuthority>) authUser.getAuthorities();
		for (GrantedAuthority a : authorities) {
			if (a.getAuthority().equalsIgnoreCase(roleName)) {
				return true;
			}
		}
		return false;
	}
	
	public static Boolean contains(Set<String> roleNames, String roleName) {
		return roleNames.contains(roleName);
	}
	
	public static String keyToString(Key key) {
		return KeyFactory.keyToString(key);
	}
	
	public static Boolean isStudentActive(Student student) {
		return student.isActive();
	}
	
	public static String formatDate(Date date) {
		if (date == null) {
			return "";
		} else {
			SimpleDateFormat f = new SimpleDateFormat("dd/MM/yyyy");
			return f.format(date);
		}
	}
	
	public static String textToString(Text text) {
		return text.getValue();
	}
	
	public static String createUploadURL(String handlerUrl) {
		BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
		return blobstoreService.createUploadUrl(handlerUrl);
	}
	
	public static Boolean isGroupIncludeCurrentStudent(GroupViewModel group) {
		if (group != null) {
			String studentId = AuthUtil.getCurrentAuthenticatedUsername();
			for (Student student : group.getStudents()) {
				if (studentId.equals(student.getStudentId())) {
					return true;
				}
			}
		}
		return false;
	}
}
